// mdn
// https://developer.mozilla.org/zh-CN/docs/Web/API/Selection
// https://developer.mozilla.org/zh-CN/docs/Web/API/Range

function ziEditer(dom,cfg){
  var obj={
    el:dom,
    sel:null,
    init:function(){
      // 设置div可写
      this.el.setAttribute('contenteditable',true)
      this.el.setAttribute('editer-root',true)
      // 插入一个p，不能是空的
      var pDom=document.createElement('p')
      pDom.innerHTML='<br>'
      this.el.append(pDom)
      // 将选区折叠
      this.sel=window.getSelection()
      this.sel.collapse(pDom,1)
      this.el.focus()
      this.el.addEventListener('mouseup',()=>{
        sel=this.sel=window.getSelection()
        if (sel.anchorNode.parentElement===sel.extentNode.parentElement && sel.type==='Range'){
          console.log(sel)
          console.log('parent',this.getParent(sel.anchorNode.parentElement))
        }
        
        
      })
    },
    getParent(dom){
      var tmp=dom
      function dg(ele){
        console.log('dg',ele)
        if (ele.parentNode.getAttribute('editer-root')){
          return
        }else{
          tmp=ele.parentNode
          dg(tmp)
        }

      }

      dg(tmp)

      return tmp
    },
    alignToRight(){
      this.sel=window.getSelection()
      sel.anchorNode.parentElement.style.textAlign="right"

    },
    alignToLeft(){
      this.sel=window.getSelection()
      sel.anchorNode.parentElement.style.textAlign="left"
    },
    alignToCenter(){
      this.sel=window.getSelection()
      sel.anchorNode.parentElement.style.textAlign="center"
    },
    toBold(){
      document.execCommand('bold')
    },
    toItalic(){

      document.execCommand('italic')
    }
  }

  obj.init()

  return obj

}